﻿using System;
using System.Collections.Generic;
using System.Text;
using Cabal.Kernel.Provider;
using System.Xml;

namespace Cabal.Kernel.Output
{
    /// <summary>
    /// 并发规则控制器
    /// </summary>
    public class RuleControl :IDisposable
    {
        public RuleControl(CabalSoul kernel, string path)
        {
            _rules = new List<IRule>();
            _kernel = kernel;
            _env = kernel.Support;
            _path = path;

            init();
        }

        public static string Regid_RuleControl = "Rules.XML";
        public static string XPath_RulesRoot = "CabalSout/Rules";
        public static string XPath_RuleType = "RuleType";
        public static string XPath_Rule = "Rule";

        public const string RType_HostIP = "HostIP";

        CabalSoul _kernel;
        EnvSupport _env;
        List<IRule> _rules;
        string _path;

        public List<IRule> Rules
        {
            get { return _rules; }
        }

        void init()
        {
            _env.Register(Regid_RuleControl, _path);

        }
        public void ReadXML()
        {
            XmlNode root = _env.ReadNode(Regid_RuleControl, XPath_RulesRoot);

            foreach (XmlNode i in root.ChildNodes)
            {
                string rtype = i.SelectSingleNode(XPath_RuleType).InnerText;
                switch (rtype)
                {
                    //目前仅有HostIP:IRule一个规则
                    case RType_HostIP:
                        IRule tmp = new HostIP(_kernel.OutputSupport.RunningMission);
                        tmp.FormXmlNode(i);
                        break;

                    default:
                        throw new Exception("读取并发规则出错");
                }
            }
        }
        public void WriteXML()
        {
            XmlNode root = _env.ReadNode(Regid_RuleControl, XPath_RulesRoot);
            root.RemoveAll();
            foreach (IRule i in _rules)
            {
                XmlNode node = _env.CreatElement(Regid_RuleControl, XPath_Rule);
                i.ToXmlNode(node);
                root.AppendChild(node);
            }
            _env.Save(Regid_RuleControl, _path);
        }

        public CheckResult Check(Mission m)
        {
            CheckResult result = CheckResult.NotApply;
            foreach (IRule i in _rules)
            {
                result = i.Check(m);
                if (result == CheckResult.Match)
                    return CheckResult.Match;
                else if (result == CheckResult.NotMatch)
                    result = CheckResult.NotMatch;
            }

            return result;
        }


        #region IDisposable 成员

        public void Dispose()
        {
            _env.UnRegister(Regid_RuleControl);
            _kernel = null;
            _env = null;
            _rules = null;
        }

        #endregion
    }
}
